<template>
  <section>
    <br />
    <el-form :model="form" ref="form" :rules="FormRules">
      <div style="border: 1px solid #e6e6e6;margin-bottom: 10px;padding:15px">
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item
              label="用例分类:"
              label-width="83px"
              prop="getCaseTypeFirstID"
            >
              <el-select
                v-model="form.getCaseTypeFirstID"
                placeholder="请选择用例分类"
              >
                <el-option
                  v-for="(item, index) in caseType"
                  :key="index + ''"
                  :label="item.code_name"
                  :value="item.code_id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="所属项目:"
              label-width="83px"
              prop="getProjectFirstID"
            >
              <el-select
                v-model="form.getProjectFirstID"
                placeholder="请选择项目列表"
              >
                <el-option
                  v-for="(item, index) in project"
                  :key="index + ''"
                  :label="item.project_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="用例名称:" label-width="83px" prop="case_name">
              <el-input
                v-model.trim="form.case_name"
                prefix-icon="el-icon-edit el-input__icon"
                placeholder="请输入用例名称"
                auto-complete
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="接口名称 :"
              label-width="83px"
              name="getApiFirstID"
            >
              <el-select
                v-model="form.getApiFirstID"
                placeholder="请选择接口名称"
                @change="getHeader"
              >
                <el-option
                  v-for="(item, index) in apiName"
                  :key="index + ''"
                  :label="item.interface_name_zh"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!--


            <el-row :span="24">
                <el-collapse v-model="activeNames" @change="handleChange">
                    <el-collapse-item title="入参header" name="1">
                        <el-table :data="form.head" highlight-current-row>
                            <el-table-column prop="value" label="key" min-width="15%" >
                                <template slot-scope="scope">
                                    <el-input v-model.trim="scope.row.header_key" :value="scope.row.header_key"  disabled></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="value" label="value" min-width="25%" >
                                <template slot-scope="scope">
                                    <el-input v-model.trim="scope.row.content" :value="scope.row.content"  prefix-icon="el-icon-edit el-input__icon" placeholder="请输入内容"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="" label="" min-width="50%" >

                            </el-table-column>
                        </el-table>
                    </el-collapse-item>
                </el-collapse>
            </el-row>  -->

      <el-row :span="24">
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item title="入参变量" name="2">
            <el-table :data="form.param" highlight-current-row>
              <el-table-column prop="value" label="key" min-width="15%">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.param_key"
                    :value="scope.row.param_key"
                    placeholder=""
                    disabled
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="value" label="value" min-width="25%">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.content"
                    :value="scope.row.content"
                    prefix-icon="el-icon-edit el-input__icon"
                    placeholder="值"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="" label="" min-width="50%">
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-row>

      <el-row :span="22">
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item title="校验" name="3">
            <div style="margin: 5px">
              <el-row :span="24"> </el-row>
            </div>
            <div
              style="border: 1px solid #e6e6e6;margin-bottom: 10px;padding:15px"
            >
              <el-row :gutter="15">
                <el-col :span="8">
                  <el-form-item
                    label="校验分类:"
                    label-width="83px"
                    name="getCheckTypeFirstID"
                  >
                    <el-select
                      v-model="form.getCheckTypeFirstID"
                      placeholder="请选择校验分类"
                      @change="changeCheckType"
                    >
                      <el-option
                        v-for="(item, index) in checkType"
                        :key="index + ''"
                        :label="item.code_name"
                        :value="item.code_id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="执行条件:"
                    label-width="83px"
                    name="ActionConditionFirstID"
                    v-if="showActionCondition"
                  >
                    <el-select
                      v-model="form.ActionConditionFirstID"
                      placeholder="选择执行条件"
                      @change="changeActionCondition"
                    >
                      <el-option
                        v-for="(item, index) in ActionCondition"
                        :key="index + ''"
                        :label="item.code_name"
                        :value="item.code_id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-table
              :data="form.responseArea"
              highlight-current-row
              v-if="ShowParameterType"
            >
              <el-table-column prop="key" label="校验Key" min-width="14%">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.key"
                    :value="scope.row.key"
                    prefix-icon="el-icon-edit el-input__icon"
                    el-
                    placeholder="请输入校验key"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="tiaojian" label="校验条件" min-width="14%">
                <template slot-scope="scope">
                  <el-select v-model="scope.row._type1" placeholder="校验条件">
                    <el-option
                      v-for="(item, index) in CheckCondition"
                      :key="index + ''"
                      :label="item.code_name"
                      :value="item.code_id"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="zhengze"
                label="预期值/正则"
                min-width="14%"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.zhengze"
                    :value="scope.row.zhengze"
                    prefix-icon="el-icon-edit el-input__icon"
                    placeholder="请输入预期值/正则"
                  ></el-input>
                </template>
              </el-table-column>
              <!--runCondition-->

              <el-table-column prop="tiaojian" label="执行条件" min-width="14%">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="runCondition"
                    :value="runCondition"
                    disabled
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="操作" min-width="5%">
                <template slot-scope="scope">
                  <i
                    class="el-icon-delete"
                    style="font-size:30px;cursor:pointer;"
                    @click="delResponse(scope.$index)"
                  ></i>
                </template>
              </el-table-column>
              <el-table-column label="" min-width="5%">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.$index === form.responseArea.length - 1"
                    size="mini"
                    class="el-icon-plus"
                    @click="addResponse"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table :data="form.sqlArea" highlight-current-row v-if="showsql">
              <el-table-column prop="sql" label="执行sql" min-width="14%">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.sql"
                    :value="scope.row.sql"
                    prefix-icon="el-icon-edit el-input__icon"
                    placeholder="请输入sql"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="sqlExpect"
                label="预期值/正则"
                min-width="14%"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.sqlExpect"
                    :value="scope.row.sqlExpect"
                    prefix-icon="el-icon-edit el-input__icon"
                    placeholder="请输入预期值/正则"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-row>
    </el-form>

    <br />
    <br />
    <!--
        <router-link :to="{ name: '接口列表', params: {project_id: this.$route.params.project_id}}" style='text-decoration: none;color: aliceblue;'>
            <el-button class="return-list" style="float: right">返回</el-button>
        </router-link>-->
    <el-button class="return-list" style="float: right" @click.native="back"
      >返回</el-button
    >

    <el-button
      class="return-list"
      type="primary"
      style="float: right; margin-right: 15px"
      @click.native="addCaseInfo"
      >保存</el-button
    >
  </section>
</template>
<!-----页面代码结束----->
<!-----脚本代码开始----->
<script>
import { test } from "../../../../api/api";
import $ from "jquery";

import {
  addCase,
  getCheckConditionList,
  addInterface,
  getProjectList,
  getModelList,
  getCheckTypeList,
  getCaseTypeList,
  getApiList,
  getActionConditionList,
} from "../../../../api/api";
export default {
  data() {
    return {
      ShowParameterType: false,
      showActionCondition: false,
      showsql: false,
      addHeaderFormVisible: false, //增加头部信息
      addParameterFormVisible: false, //增加入参
      activeNames: ["1", "2", "3"],
      CheckCondition: [],
      ActionCondition: [],

      //radio: "form-data",
      addHeaderFormVisible: false, //增加头部信息
      addParameterFormVisible: false, //增加入参
      radioType: "",
      result: true,
      activeNames: ["1", "2", "3", "4", "5", "6"],
      id: "",
      runCondition: "",
      request3: false,
      selectable: false,
      flag: true,
      //aaaa:true,
      // vm.$set(vm.items, indexOfItem, newValue)
      form: {
        head: [],
        param: [],

        getProjectFirstID: "", //所属项目
        getApiFirstID: "", //接口名称
        getCaseTypeFirstID: "", //用例分类
        //getModelFirstID:'',
        case_name: "", //用例名称
        status: 0, //状态
        responseArea: [
          { key: "", exetiaojian: "_type2", zhengze: "", tiaojian: "" }, //, //依赖默认给1
        ],

        sqlArea: [
          { sql: "", zhengze: "" }, //依赖默认给1
        ],
        status: true,
        requestType: "POST",
        httpType: "HTTP",
        apiAddress: "",
        selectable: false,
        //默认check属性yilai=0  不要勾选 不存在依赖

        data: "",
      },
      FormRules: {
        case_name: [
          { required: true, message: "请输入用例名称", trigger: "blur" },
          { max: 50, message: "不能超过50个字", trigger: "blur" },
        ],

        //apiAddress : [{ required: false, message: '请输入地址', trigger: 'blur' }],
        //required : [{ type: 'boolean', required: false, message: '请选择状态', trigger: 'blur' }],
        getModelFirstID: [
          {
            type: "number",
            required: true,
            message: "请选择项目模块",
            trigger: "blur",
          },
        ],
        getProjectFirstID: [
          {
            type: "number",
            required: true,
            message: "请选择项目",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    cellcb(row) {
      if (row.row.checkStatus === 1 && row.columnIndex === 0) {
        return "myCell";
      }
    },

    checkRequest() {
      let request = this.form.requestType;
      if (request === "GET" || request === "DELETE") {
        this.request3 = false;
      } else {
        this.request3 = true;
      }
    },
    isJsonString(str) {
      try {
        if (typeof JSON.parse(str) === "object") {
          return true;
        }
      } catch (e) {}
      return false;
    },

    handleResponseEdit: function(index, row) {
      this.yilaiVisible = true;
      this.id = index;
    },

    addCaseInfo: function() {
      //保存按钮***********

      if (this.form.data) {
        if (!this.isJsonString(this.form.data)) {
          this.$message({
            message: "数据错误",
            center: true,
            type: "error",
          });
        } else {
          this.addApi();
        }
      } else if (this.form.data) {
        this.$message({
          message: "数据不全",
          center: true,
          type: "warning",
        });
      } else {
        this.addCases();
      }
    },

    addCases: function() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let self = this;

          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            self.form.parameterType = self.radio;
            let _type = self.form.parameterType;
            let _type1 = self.form.CheckCondition;
            let _type2 = self.form.CheckCondition;
            let _parameter = {};
            _parameter = self.form.requestList;

            let params = {
              //构建参数

              getCheckTypeFirstID: Number(self.form.getCheckTypeFirstID),
              ActionConditionFirstID: Number(self.form.ActionConditionFirstID),
              getModelFirstID: Number(self.form.getModelFirstID),
              getProjectFirstID: Number(self.form.getProjectFirstID),
              getCaseTypeFirstID: Number(self.form.getCaseTypeFirstID),
              getApiFirstID: Number(self.form.getApiFirstID),
              case_name: self.form.case_name,

              sqlArea: self.form.sqlArea,
              responseArea: self.form.responseArea,

              head: self.form.head,
              param: self.form.param,

              requestType: self.form.requestType,
              header_key: self.form.header_key,
              requestList: _parameter,

              data: self.form.data,
            };
            let headers = {
              "Content-Type": "application/json",
              Authorization:
                "Token " + JSON.parse(sessionStorage.getItem("token")),
            };

            addCase(headers, params).then((_data) => {
              //    更新detail
              let { msg, code, data } = _data;

              if (code === "999999") {
                self.$message({
                  message: "保存成功",
                  center: true,
                  type: "success",
                });
                this.$router.go(-1);
              } else {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              }
            });
          });
        }
      });
    },
    getProjects() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getProjectList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          var projectjsonArr = new Array();

          for (var i = 0; i < data.length; i++) {
            if (data[i].status == 0) {
              projectjsonArr.push(data[i]);
            }
          }

          self.project = projectjsonArr;
          self.form.getProjectFirstID = self.project[0].id;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    getApis() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };

      getApiList(headers, params).then((_data) => {
        let { msg, code, data } = _data;

        if (code === "999999") {
          var apijsonArr = new Array();

          for (var i = 0; i < data.length; i++) {
            if (data[i].delete_flag == 0) {
              apijsonArr.push(data[i]);
            }
          }

          self.apiName = apijsonArr;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    //校验条件

    getCheckConditions() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };

      getCheckConditionList(headers, params).then((_data) => {
        let { msg, code, data } = _data;

        if (code === "999999") {
          self.CheckCondition = data;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    //执行条件

    getActionConditions() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };

      getActionConditionList(headers, params).then((_data) => {
        let { msg, code, data } = _data;

        if (code === "999999") {
          self.ActionCondition = data;

          //self.form.ActionConditionFirstID = self.ActionCondition[0].code_id
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    getCheckType() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getCheckTypeList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          self.checkType = data;

          // self.form.getCheckTypeFirstID = self.checkType[0].code_id
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    getCaseType() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getCaseTypeList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          self.caseType = data;

          self.form.getCaseTypeFirstID = self.caseType[0].code_id;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    changeCheckType(label) {
      //action_condition  1与0或
      //check_type  0response 1 database
      if (label === "0") {
        //*******db
        (this.ShowParameterType = true),
          (this.showsql = false),
          (this.showActionCondition = true);
      } else if (label === "1") {
        //***********数据库修改这个一定要变
        (this.ShowParameterType = false),
          (this.showActionCondition = false),
          (this.showsql = true);
      } else {
        (this.ShowParameterType = false),
          (this.showActionCondition = false),
          (this.showsql = false);
      }
    },

    changeActionCondition(value) {
      let obj = this.ActionCondition.find((i) => {
        return i.code_id === value;
      });
      let runCondition = obj.code_name;
      this.runCondition = runCondition;
      this.$forceUpdate();
    },

    getHeader(value) {
      let self = this;
      let param = { interfaceId: value };

      $.ajax({
        type: "get",
        url: test + "/api/api/case_getHeader",

        async: true,
        data: param,
        headers: {
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        },
        timeout: 5000,
        success: function(data) {
          if (data.code === "999999") {
            var dataHeader = data.data.header;
            //self.id = data.id;

            if (dataHeader.length) {
              self.form.head = dataHeader;
            }

            var dataParam = data.data.params;
            // self.id = dataParam.id;

            if (dataParam.length) {
              self.form.param = dataParam;
              //  this.$set(this.param)
            }

            // this.getdata();
            // this.$forceUpdate();
          } else {
            self.$message.error({
              message: data.msg,
              center: true,
            });
          }
        },
      });
      //step2
      //$.ajax({
      //    type: "get",
      //    url: test+"/api/api/case_getParam",
      //    async: true,
      //   data: param,
      //   headers: {
      //      Authorization: 'Token '+JSON.parse(sessionStorage.getItem('token'))
      //   },
      //   timeout: 5000,
      //   success: function(data) {

      //      if (data.code === '999999') {
      //         data = data.data;
      //         self.id = data.id;
      //        if (data.length) {
      //           self.form.param = data;
      //       }

      //   }
      //  else {
      //   self.$message.error({
      //       message: data.msg,
      //        center: true,
      //    })
      //    }
      // },

      // });
    },
    addResponse() {
      //responseArea
      let headers = { key: "", zhengze: "", tiaojian: "" };
      this.form.responseArea.push(headers);
    },
    delResponse(index) {
      this.form.responseArea.splice(index, 1);
      if (this.form.responseArea.length === 0) {
        this.form.responseArea.push({ key: "", zhengze: "", tiaojian: "" });
      }
    },

    editParameterSubmit: function() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.form.requestList[this.id] = this.editForm;
          this.addParameterFormVisible = false;
        }
      });
    },
    handleParameterEdit: function(index, row) {
      this.addParameterFormVisible = true;
      this.id = index;
      this.editForm = Object.assign({}, row);
    },

    // demo  下拉菜单从数据库取值

    back() {
      this.$router.go(-1);
    },

    addParameter() {
      //{name: "", _type:"String", yilai: "0",yilaijiekou:""},
      // {name: "",_type:"String", yilai: "0",yilaijiekou:""}
      let headers = {
        name: "",
        value: "",
        _type: "String",
        yilai: "0",
        yilaijiekou: "",
      };

      this.form.requestList.push(headers);
    },

    delParameter(index) {
      this.form.requestList.splice(index, 1);
      if (this.form.requestList.length === 0) {
        this.form.requestList.push({
          name: "",
          value: "",
          _type: "String",
          yilai: "0",
          yilaijiekou: "",
        });
      }
    },

    cellcb(index) {
      // txt.style.display = "none";
      //this.form.responseList.splice(index, 1);

      if (index.row.checkStatus === 1 && index.row.columnIndex === 0) {
        return "myCell";
      }
    },

    changeParameterType() {
      //不要删除这个加密URL用的到
      if (this.radio === "form-data") {
        this.ParameterType = true;
      } else {
        this.ParameterType = false;
      }
    },
    showData() {
      this.result = true;
    },
    showHead() {
      this.result = false;
    },
    handleChange(val) {},
    onSubmit() {},
  },
  watch: {
    radio() {
      this.changeParameterType();
    },
  },
  mounted() {
    this.getProjects();
    // this.getModels();
    this.getCaseType();
    this.getApis();
    this.getHeader();
    this.getCheckType();
    this.getActionConditions();
    this.getCheckConditions();
    this.getActionConditions();
  },
};
</script>
<!--style 样式-->
<style lang="scss" scoped>
.return-list {
  margin-top: 0px;
  margin-bottom: 10px;
  border-radius: 25px;
}
.head-class {
  font-size: 17px;
}
.parameter-a {
  display: block;
}
.parameter-b {
  display: none;
}
.selectInput {
  position: absolute;
  /*margin-left: 7px;*/
  padding-left: 9px;
  width: 180px;
  /*border-radius:0px;*/
  /*height: 38px;*/
  left: 1px;
  border-right: 0px;
}
</style>
<style lang="scss">
.selectInput {
  input {
    border-right: 0px;
    border-radius: 4px 0px 0px 4px;
  }
}
</style>

<style>
.myCell .el-checkbox__input {
  display: none;
}
</style>
